package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/23 11:06
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> stream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream);
        tEnv.createTemporaryView("sensor", table);
        // 1. table api中不使用
        /*table
            .groupBy($("id"))
            .select($("id"), call(MyAvg.class, $("vc")).as("sum_vc"))
            .execute()
            .print();*/
        // 2.sql中使用
        tEnv.createTemporaryFunction("my_avg", MyAvg.class);
        
        tEnv.sqlQuery("select id, my_avg(vc) m_avg from sensor group by id").execute().print();
        
        
    }
    
    public static class MyAvg extends AggregateFunction<Double, Avg> {
        // 创建累加器  初始化累累加器
        // 每个key执行一次
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        
        // 返回最终结果
        
        @Override
        public Double getValue(Avg acc) {
            return acc.sum * 1.0 / acc.count;
        }
        
        // 用来对需要聚合的值进行聚合
        // 返回值必须是void 方法名必须是: accumulate
        // 参数列表: 第一个必须是累加器  从第二个开始,就是需要聚合的元素
        
        public void accumulate(Avg acc, Integer vc) {
            acc.sum += vc;
            acc.count++;
        }
        
    }
    
    public static class Avg {
        public Integer sum = 0;
        public Long count = 0L;
    }
    
}
